package com.leyou.upload.service;

import com.aliyun.oss.OSS;
import com.aliyun.oss.common.utils.BinaryUtil;
import com.aliyun.oss.model.MatchMode;
import com.aliyun.oss.model.PolicyConditions;
import com.leyou.common.enums.ExceptionEnum;
import com.leyou.common.exception.LyException;
import com.leyou.upload.properties.OSSProperties;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;

/**
 * @author by my
 * @Description TODO
 * @Date 2020/3/30 11:09
 */
@Service
public class UploadService {
    @Autowired
    private OSS oss;
    @Autowired
    private OSSProperties properties;

    /**
     * 图片存放的路径
     */
    public static final String IMAGE_PATH = "D:\\Software\\nginx-1.16.0\\html\\upload\\brand-img\\";
    /**
     * 图片返回的路径
     */
    public static final String IMAGE_URL = "http://image.leyou.com/upload/brand-img/";
    /**
     * 文件的类型
     */
    private static final List<String> ALLOW_IMAGE_TYPE = Arrays.asList("image/jpeg", "image/png");

    public String upload(MultipartFile file) {
        // 判断文件的类型
        if (!ALLOW_IMAGE_TYPE.contains(file.getContentType())) {
            // 没找到当前文件的类型
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        // 解析上传的图片是否是图片
        try {
            BufferedImage bufferedImage = ImageIO.read(file.getInputStream());
            if (bufferedImage == null) {
                // 没找到当前文件的类型
                throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
            }
        } catch (IOException e) {
            e.printStackTrace();
            // 没找到当前文件的类型
            throw new LyException(ExceptionEnum.INVALID_FILE_TYPE);
        }

        //得到文件上传的文件对象：路径
        File imagePathFile = new File(IMAGE_PATH);

        // 获取文件名并重新设置文件名
        String fileName = UUID.randomUUID() + file.getOriginalFilename();
        // 上传文件
        try {
            file.transferTo(new File(imagePathFile, fileName));
        } catch (IOException e) {
            e.printStackTrace();
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
        // 返回图片访问路径
        return IMAGE_URL + fileName;
    }

    public Map<String, String> signature() {
        try {
            // 过去时间
            long expireTime = properties.getExpireTime();
            // 把过期时间转为毫秒数
            long expireEndTime = System.currentTimeMillis() + expireTime * 1000;
            Date expiration = new Date(expireEndTime);
            PolicyConditions policyConds = new PolicyConditions();
            // 上传大小
            policyConds.addConditionItem(PolicyConditions.COND_CONTENT_LENGTH_RANGE, 0, properties.getMaxFileSize());
            // 目录
            policyConds.addConditionItem(MatchMode.StartWith, PolicyConditions.COND_KEY, properties.getDir());

            //生成上传策略
            String postPolicy = oss.generatePostPolicy(expiration, policyConds);
            // 编码格式
            byte[] binaryData = postPolicy.getBytes("utf-8");
            // 把数据转为base64
            String encodedPolicy = BinaryUtil.toBase64String(binaryData);
            // 生成签名
            String postSignature = oss.calculatePostSignature(postPolicy);

            Map<String, String> respMap = new LinkedHashMap<>();
            // 注意这里要和乐优前端获取的key一致
            respMap.put("accessId", properties.getAccessKeyId());
            respMap.put("policy", encodedPolicy);
            respMap.put("signature", postSignature);
            respMap.put("dir", properties.getDir());
            respMap.put("host", properties.getHost());
            respMap.put("expire", String.valueOf(expireEndTime));

            return respMap;
        } catch (Exception e) {
            throw new LyException(ExceptionEnum.FILE_UPLOAD_ERROR);
        }
    }
}
